﻿using Adp;
using Adp.Common;
using Microsoft.AspNetCore.Mvc;
using Yqd.Models;
using System;
using System.Linq;
using Yqd.Enm;
using Yqd.Core;
using Yqd.Controllers.Filter;
using Newtonsoft.Json.Linq;
using Adp.Models;
using System.Collections;
using System.Collections.Generic;
using System.IO;

namespace Yqd.Controllers
{
    [Area("Yqd")]
    public class WxUserController : Controller
    {
        TcmContext tcm;
        YqdContext ctx;
        DdService ddService;
        int count = 0;

        public WxUserController(TcmContext tcm, YqdContext ctx, DdService ddService)
        {
            this.tcm = tcm;
            this.ctx = ctx;
            this.ddService = ddService;
        }

        public ActionResult Login()
        {
            var code = Form.GetString("auth_code");
            var EmployeeCode = Form.GetString("EmployeeCode", "GE_a6dabcc3edce4ebea9775dfa26ed99ed");
            YqdUser user = null;
            if (code.HasValue()) user = ddService.GetAppUser(code);
            else if (EmployeeCode.HasValue())
            {
                var su = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == EmployeeCode && it.Status == 用户状态.使用中);
                if (su != null)
                {
                    var unit = ctx.Yqd_Unit.FirstOrDefault(it => it.OrganizationCode == su.UnitCode);
                    string UnitCode = "", UnitName = "";
                    if (unit != null)
                    {
                        UnitCode = unit.UnitCode;
                        UnitName = unit.Name;
                    }
                    user = new YqdUser
                    {
                        Role = new List<角色类型>(),
                        Permit = new List<权限清单>(),
                        Avatar = su.Avatar,
                        Name = su.Name,
                        AccountId = su.AccountId,
                        UnitCode = UnitCode,
                        UnitName = UnitName,
                        OrganizationCode = su.UnitCode,
                        EmployeeCode = su.EmployeeCode
                    };
                    if (!string.IsNullOrWhiteSpace(su.Roles))
                    {
                        user.Role = su.Roles.Split(",").Select(it => (角色类型)int.Parse(it)).ToList();
                    }
                    if (!string.IsNullOrWhiteSpace(su.PermitItem))
                    {
                        user.Permit = su.PermitItem.Split(",").Select(it => (权限清单)int.Parse(it)).ToList();
                    }
                }
            }
            if (user != null)
            {
                LoggingService.AddLog(user.EmployeeCode);
                if (user.Role.Any(it => it > 角色类型.未设置 && it < 角色类型.协调人))
                {
                    WxUser.LoginMini(user);
                    return this.ToJson(new
                    {
                        success = true,
                        url = WxUser.RedirectUrl
                    });
                }
            }
            return this.ToJson(new
            {
                success = false,
                message = "您暂无权限访问，请与管理员联系！"
            });
        }

        [User(false)]
        public ActionResult GetUser()
        {
            var user = WxUser.LogonInfo;
            var Avatar = "";
            if (!string.IsNullOrWhiteSpace(user.Avatar))
            {
                var rootPath = Env.ServerRoot.Combine("wwwroot");
                var filepath = "/Client/Yqd/Avatar/";
                var path = rootPath + filepath;
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                var filename = user.EmployeeCode + ".jpg";
                path += filename;
                if (!System.IO.File.Exists(path))
                {
                    ddService.GenerateAvatar(user.Avatar, path);
                }
                Avatar = filepath + filename;
            }
            return this.ToJson(new
            {
                success = true,
                user.EmployeeCode,
                Avatar,
                user.Name,
                user.UnitCode,
                user.UnitName,
                user.OrganizationCode,
                WxUser.Platform
            });
        }

        public ActionResult GetAccountID()
        {
            var code = Form.GetString("auth_code");
            var AccountId = "";
            if (code.HasValue()) {
                var user = ddService.GetAppUser(code);
                if (user != null) AccountId = user.AccountId.ToString();
            }
           
            return this.ToJson(new
            {
                success = true,
                AccountId
            });
        }

        public ActionResult LoginOut()
        {
            WxUser.LoginOut();
            return this.ToJson(new
            {
                success = true
            });
        }

        [User]
        public ActionResult GetOrgUser()
        { 
            var level = Form.GetInt("Level", 0);
            var ShowUser = Form.GetBool("ShowUser", false);
            var OrgCode = Form.GetString("OrgCode");
            if (level == 0)
            {
                var data = new List<object>();
                OrgCode = WxUser.LogonInfo.OrganizationCode;
                var d = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == OrgCode);
                if (d != null)
                {
                    data.Add(new
                    {
                        d.OrganizationCode,
                        label = d.Name,
                        Level = 1,
                        ShowUser = false,
                        d.isLeaf
                    });
                }
                return this.ToJson(new
                {
                    success = true,
                    data
                });
            }
            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            if (ShowUser)
            {
                var arr = ddService.pageOrganizationEmployeePositions(OrgCode, config.TenantId);
                var data = new ArrayList();
                foreach (var o in arr)
                {
                    data.Add(new
                    {
                        OrganizationCode = o["employeeCode"].ToString(),
                        EmployeeCode = o["employeeCode"].ToString(),
                        label = o["employeeName"].ToString(),
                        Level = 3,
                        ShowUser = false,
                        isLeaf = true
                    });
                }
                return this.ToJson(new
                {
                    success = true,
                    data
                });
            }
            var dept = ctx.Yqd_Department.Where(it => it.ParentCode == OrgCode);
            return this.ToJson(new
            {
                success = true,
                data = dept.ToList().Select(it => new
                {
                    it.OrganizationCode,
                    label = it.Name,
                    Level = 2,
                    ShowUser = it.isLeaf,
                    isLeaf = false
                })
            });
        }

        protected bool HasUser(string OrganizationCode, (string AppKey, string AppSecret, int TenantId) config)
        {
            var arr = ddService.pageOrganizationEmployeeCodes(OrganizationCode, config.TenantId);
            return arr.Count() == 0;
        }

        public ActionResult UpdateLevel()
        {
            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            UpdateConfig("单位级别", ddService.queryByPropertyCode("govInstitutionLevel", config.TenantId));
            UpdateConfig("人员编制", ddService.queryByPropertyCode("govEmpBudgetedPost", config.TenantId));
            UpdateConfig("职级", ddService.queryByPropertyCode("govEmpJobLevel", config.TenantId));
            UpdateConfig("性别", ddService.queryByPropertyCode("govEmpGender", config.TenantId));
            UpdateConfig("政治面貌", ddService.queryByPropertyCode("govEmpPoliticalStatus", config.TenantId));
            UpdateConfig("任职类型", ddService.queryByPropertyCode("govJobAttributes", config.TenantId));
            UpdateConfig("人员角色", ddService.queryByPropertyCode("govEmpPosEmployeeRole", config.TenantId));
            UpdateConfig("职务层次", ddService.queryByPropertyCode("govEmpJobRank", config.TenantId));
            UpdateConfig("可见性标识", ddService.queryByPropertyCode("visibilityIndicator", config.TenantId));

            return this.ToJson(new
            {
                success = true
            });
        }
        public ActionResult UpdateAllDepartment()
        {
            var config = Config.AppSecret(AccessTokenMode.浙政钉通讯录);
            var sc = ddService.scopesV2(config.TenantId);
            foreach (var item in sc["deptVisibleScopes"])
            {
                UpdateDepartment("", item.ToString(), config.TenantId);
                LoadDepartment(item.ToString(), config.TenantId);
            }
            return this.ToJson(new
            {
                success = true
            });
        }
        private void LoadDepartment(string organizationCode, int tenantId)
        {
            var data = ddService.pageSubOrganizationCodes(organizationCode, tenantId);
            foreach (var item in data)
            {
                if(UpdateDepartment(organizationCode, item, tenantId))
                {
                    //UpdateEmployee(organizationCode, item, tenantId);
                }
                LoadDepartment(item.ToString(), tenantId);
            }
        }
        private bool UpdateDepartment(string parentCode, string organizationCode, int tenantId)
        {
            var info = ddService.GetOrganizationInfo(organizationCode, tenantId);
            if (info != null)
            {
                var code = info["institutionLevelCode"]?.ToString() ?? "";
                var org = ctx.Yqd_Department.FirstOrDefault(it => it.OrganizationCode == organizationCode);
                if (org == null)
                {
                    ctx.Yqd_Department.Add(new Yqd_Department
                    {
                        OrganizationCode = organizationCode,
                        ParentCode = parentCode,
                        Name = info["organizationName"].ToString(),
                        InstitutionLevelCode = code,
                        InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code),
                        TypeCode = info["typeCode"]?.ToString() ?? "",
                        TypeName = info["typeName"]?.ToString() ?? ""
                    });
                    SaveChanges();
                    return true;
                }
                //else
                //{
                //    org.Name = info["organizationName"].ToString();
                //    org.InstitutionLevelCode = code;
                //    org.InstitutionLevelName = ddService.GetPropertyNameByCode("单位级别", code);
                //    org.TypeCode = info["typeCode"]?.ToString() ?? "";
                //    org.TypeName = info["typeName"]?.ToString() ?? "";
                //}
            }
            return false;
        }

        private void UpdateEmployee(string parentCode, string organizationCode, int tenantId)
        {
            var data = ddService.pageOrganizationEmployeeCodes(organizationCode, tenantId);
            foreach (var EmployeeCode in data)
            {
                var info = ddService.GetEmployeeInfo(EmployeeCode, tenantId);
                var empJobLevelCode = info["empJobLevelCode"]?.ToString() ?? "";
                var empBudgetedPostCode = info["empBudgetedPostCode"]?.ToString() ?? "";

                var code = info["institutionLevelCode"]?.ToString() ?? "";
                var emp = ctx.Yqd_User.FirstOrDefault(it => it.EmployeeCode == EmployeeCode);
                if (emp == null)
                {
                    ctx.Yqd_User.Add(new Yqd_User
                    {
                        AccountId = 0,
                        Openid = "",
                        Roles = "0",
                        EmployeeCode = EmployeeCode,
                        Name = info["employeeName"].ToString(),
                        Avatar = info["govEmpAvatar"]?.ToString() ?? "",
                        Gender = info["empGender"].ToString().ToInt(),
                        OrganizationCode = organizationCode,
                        empJobLevelCode = empJobLevelCode,
                        empBudgetedPostCode = empBudgetedPostCode,
                        empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode),
                        empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode)
                    });
                    SaveChanges();
                }
                //else
                //{
                //    emp.Name = info["employeeName"].ToString();
                //    emp.Avatar = info["govEmpAvatar"]?.ToString() ?? "";
                //    emp.Gender = info["empGender"].ToString().ToInt();
                //    emp.OrganizationCode = organizationCode;
                //    emp.empJobLevelCode = empJobLevelCode;
                //    emp.empBudgetedPostCode = empBudgetedPostCode;
                //    emp.empJobLevelName = ddService.GetPropertyNameByCode("职级", empJobLevelCode);
                //    emp.empBudgetedPostName = ddService.GetPropertyNameByCode("人员编制", empBudgetedPostCode);
                //}
            }
        }
        private void SaveChanges()
        {
            ctx.SaveChanges();
            if (count++ >= 100)
            {
                count = 0;
                //ctx = new SqmyContext();
            }
        }
        private void UpdateConfig(string type, JArray data)
        {
            var ct = tcm.ConfigType.Where(it => it.PlusID == "Yqd" && it.Groupname == "枚举字典" && it.Name == type);
            tcm.ConfigType.RemoveRange(ct);
            var cc = tcm.Config.Where(it => it.PlusID == "Yqd" && it.Groupname == "枚举字典" && it.Name == type);
            tcm.Config.RemoveRange(cc);
            tcm.SaveChanges();
            var id = DAL.MaxID();
            tcm.ConfigType.Add(new Tcm_ConfigType
            {
                ConfigTypeID = id,
                PlusID = "Yqd",
                Name = type,
                Groupname = "枚举字典",
                Locked = false,
                Tactic = id,
                Modtime = DateTime.Now,
                Creator = 1
            });
            tcm.SaveChanges();
            foreach (var item in data)
            {
                var cid = DAL.MaxID();
                tcm.Config.Add(new Tcm_Config
                {
                    ConfigID = cid,
                    ConfigTypeID = id,
                    PlusID = "Yqd",
                    ConfigTypeName = type,
                    Groupname = "枚举字典",
                    Name = item["code"].ToString(),
                    Value = item["name"].ToString(),
                    Locked = false,
                    Tactic = cid,
                    Modtime = DateTime.Now,
                    Creator = 1,
                    Disabled = false
                });
            }
            tcm.SaveChanges();
        }
    }
}
